package com.android.lovely.ui.adapter

import android.annotation.SuppressLint
import androidx.core.view.get
import coil.load
import com.android.lovely.R
import com.android.lovely.admob.AdmobManager
import com.android.lovely.data.LovelyTask
import com.android.lovely.databinding.ItemLovelyTaskBinding
import com.android.lovely.framework.BaseAdapter
import com.kotlin.extensions.appContext
import com.kotlin.extensions.coroutine.CoroutineExt.launchSafety
import com.kotlin.extensions.view.ViewExt.clickable
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.collectLatest
import java.util.Locale

class TaskAdapter(scope: CoroutineScope) : BaseAdapter<LovelyTask, ItemLovelyTaskBinding>() {

    private var isChatAdEnable = false
        set(value) {
            field = value
            notifyItemChanged(maxOf(getItems().indexOfFirst { it.isChatAd() }, 0))
        }

    init {
        scope.launchSafety {
            AdmobManager.chatAdEnableFlow.collectLatest {
                isChatAdEnable = it
            }
        }
    }

    private fun LovelyTask.isChatAd(): Boolean {
        return type == "ad_chat_page"
    }

    @SuppressLint("SetTextI18n")
    override fun bindViewWithHolderDetails(holder: ViewHolder, item: LovelyTask?, binding: ItemLovelyTaskBinding, position: Int) {
        item ?: return
        binding.apply {
            icon.load(item.icon.substringBefore("?")) { crossfade(true) }
            title.text = "${item.title} (${if (item.maxNum > 0) "${item.num}/${item.maxNum}" else appContext.getString(R.string.unlimit)})"
            gens.text = item.point.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString() }
            content.text = item.msg
            get.isEnabled = if (item.isChatAd()) isChatAdEnable else item.maxNum == 0 || item.num < item.maxNum || item.type == "enter_code"
            root.isClickable = false
            get.clickable { onItemClick?.invoke(item, position) }
        }
    }
}